import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Tabs, Row } from 'antd';
import _ from 'lodash';
import moment from 'moment';
import React, { PureComponent } from 'react';

import style from './index.less';
import Assets from './tab/Assets';
import Bond from './tab/Bond';
// eslint-disable-next-line no-unused-vars
import BondLending from './tab/BondLending';
import DepositMoney from './tab/DepositMoney';
import DirectFinancing from './tab/DirectFinancing';
import Etf from './tab/Etf';
import ExchangeNegotiatedRepo from './tab/ExchangeNegotiatedRepo';
import ExchangeRepo from './tab/ExchangeRepo';
import InterbankRepo from './tab/InterbankRepo';
import Nonstandard from './tab/Nonstandard';
import OutsideFunds from './tab/OutsideFunds';
import Stock from './tab/Stock';
import StockFuture from './tab/stockFuture';
// eslint-disable-next-line no-unused-vars
import WeiWaiPost from './tab/WeiWaiPost';

import { DATA_ENTRY, ContentPackage, AdvancedSearch, codeType, TabC } from '../../../comps';
import investmentTypeData from '../../../utils/enumeratedValues/investmentType';

const { TabPane } = Tabs;

@Form.create()
export default class PositionInquiry extends PureComponent {
  constructor(props) {
    super(props);
    this.commonArgs = {};
    this.state = {
      activeKey: 'Bond',
      bondArgs: {}, // 债券参数
      outsideFundsArgs: {}, // 场外基金参数
      etfArgs: {}, // ETF参数
      depositMoneyArgs: {}, // 存款参数
      assetplanArgs: {}, // 理财/资产计划参数
      interbankRepoArgs: {}, // 银行间回购参数
      exchangeRepoArgs: {}, // 交易所回购参数
      exchangeNegotiatedRepoArgs: {}, // 交易所协议回购参数
      directFinancingArgs: {}, // 理财直融参数
      nonstandardArgs: {}, // 非标参数
      stockArgs: {}, // 股票参数
      bondLendingArgs: {}, // 债券借贷参数
      WeiWaiPostArgs: {}, // 委外投资参数
      stockFutureArgs: {}, // 股指期货
      securityType: '', // 选择的证券代码类型
      HkStkType: '0', // 这个是记录，目前是a股还是h股
    };
  }

  componentDidMount() {
    if (sessionStorage.getItem('Stock')) {
      sessionStorage.removeItem('Stock');
    }
    const startDate = moment().format('YYYY-MM-DD');
    const endDate = moment().format('YYYY-MM-DD');
    const timestamp = new Date().getTime(); // 时间戳,点查询的时候 不管条件有没有改变 都有触发查询
    this.commonArgs = { startDate, endDate, timestamp };
    this.getTableData();
  }

  componentWillUnmount() {
    if (sessionStorage.getItem('Stock')) {
      sessionStorage.removeItem('Stock');
    }
    sessionStorage.removeItem('JYLS_pageJump');
  }

  componentDidUpdate() {
    // 页面判断是否从人行跳转过来
    if (sessionStorage.getItem('JYLS_pageJump')) {
      const item = JSON.parse(sessionStorage.getItem('JYLS_pageJump'));
      sessionStorage.removeItem('JYLS_pageJump');
      this.setState(
        {
          activeKey: item.tabKey, // 定位tab
        },
        () => {
          const {
            form: { setFieldsValue },
          } = this.formGroupThis.props;
          if (item.exchangeCodeObj) {
            setFieldsValue({ tradingCode: `${item.exchangeCodeObj.exchangeCode}-${item.exchangeCodeObj.tradingCode}` });
            this.commonArgs.exchangeCode = item.exchangeCodeObj ? item.exchangeCodeObj.exchangeCode : this.commonArgs.exchangeCode;
            this.commonArgs.tradingCode = item.exchangeCodeObj ? item.exchangeCodeObj.tradingCode : this.commonArgs.tradingCode;
          } else {
            setFieldsValue({ tradingCode: undefined });
            this.commonArgs.exchangeCode = undefined;
            this.commonArgs.tradingCode = undefined;
          }
          // 判断跳转是否带有日期
          if (item.startDate) {
            // 改变页面开始时间
            // eslint-disable-next-line max-len
            this.state.date?.setDate([
              item.startDate ? moment(item.startDate) : moment(this.commonArgs.startDa),
              item.endDate ? moment(item.endDate) : moment(this.commonArgs.endDate),
            ]);
            // 改变查询条件
            this.commonArgs.startDate = item.startDate ? item.startDate : this.commonArgs.startDa;
            this.commonArgs.endDate = item.endDate ? item.endDate : this.commonArgs.endDate;
          }
          // cpCode存在
          if (item.cpCode.some((i) => i !== '')) {
            this.state.AdvancedSearchFormBeanRef?.props?.form?.setFieldsValue({
              cpCode: item.cpCode,
            });

            this.commonArgs.cpCode = item.cpCode;
          }
          this.getTableData();
        },
      );
    }
  }

  zqCodeChange = (e) => {
    if (e && e.securityType) {
      this.setState({
        securityType: e.securityType,
      });
    }
    // 改变的时候需要定位到a股还是h股的位置
    if (e && e.exchangeCode) {
      if (e.exchangeCode == '162' || e.exchangeCode == '166' || e.exchangeCode == '161') {
        // 此时是港股
        this.setState({
          HkStkType: '1',
        });
      } else if (e.exchangeCode == '101' || e.exchangeCode == '105') {
        // 此时是a股
        this.setState({
          HkStkType: '0',
        });
      }
    }
  };

  getTableData = () => {
    const { activeKey, childrenactiveKey } = this.state;
    if (activeKey == 'Bond') {
      this.setState({
        bondArgs: _.cloneDeep(this.commonArgs),
      });
    }
    if (activeKey == 'Etf') {
      this.setState({
        etfArgs: _.cloneDeep(this.commonArgs),
      });
    }

    if (activeKey == 'DepositMoney') {
      this.setState({
        depositMoneyArgs: _.cloneDeep(this.commonArgs),
      });
    }
    if (activeKey == 'InterbankRepo') {
      this.setState({
        interbankRepoArgs: _.cloneDeep(this.commonArgs),
      });
    }
    if (activeKey == 'DirectFinancing') {
      this.setState({
        directFinancingArgs: _.cloneDeep(this.commonArgs),
      });
    }
    if (activeKey == 'Stock') {
      this.setState({
        stockArgs: _.cloneDeep(this.commonArgs),
      });
    }
    if (activeKey == 'BondLending') {
      this.setState({
        bondLendingArgs: _.cloneDeep(this.commonArgs),
      });
    }
    if (activeKey == 'Assets') {
      this.setState({
        AssetsArgs: _.cloneDeep(this.commonArgs),
      });
    }
    if (activeKey == 'WeiWaiPost') {
      this.setState({
        WeiWaiPostArgs: _.cloneDeep(this.commonArgs),
      });
    }
    if (activeKey == 'OutSourcing') {
      this.setState({
        outSourcingArgs: _.cloneDeep(this.commonArgs),
      });
    }
    if (activeKey == 'StockFuture') {
      this.setState({
        stockFutureArgs: _.cloneDeep(this.commonArgs),
      });
    }
    if (childrenactiveKey == 'OutsideFunds') {
      this.setState({
        outsideFundsArgs: _.cloneDeep(this.commonArgs),
      });
    }
    if (childrenactiveKey == 'ExchangeRepo') {
      this.setState({
        exchangeRepoArgs: _.cloneDeep(this.commonArgs),
      });
    }
    if (childrenactiveKey == 'ExchangeNegotiatedRepo') {
      this.setState({
        exchangeNegotiatedRepoArgs: _.cloneDeep(this.commonArgs),
      });
    }
    if (childrenactiveKey == 'Nonstandard') {
      this.setState({
        nonstandardArgs: _.cloneDeep(this.commonArgs),
      });
    }
  };

  // 父tab切换
  tabOnclick = (e) => {
    this.setState(
      {
        activeKey: e,
        childrenactiveKey: e,
      },
      () => {
        this.getTableData();
      },
    );
  };

  // 子tab切换
  childrentabOnclick = (e) => {
    this.setState(
      {
        childrenactiveKey: e,
      },
      () => {
        this.getTableData();
      },
    );
  };

  // 点击搜索
  getSearchData = (e) => {
    if (sessionStorage.getItem('Stock')) {
      sessionStorage.removeItem('Stock');
    }
    if (e && e.startDate && e.endDate) {
      e.startDate = moment(e.startDate).format('YYYY-MM-DD');
      e.endDate = moment(e.endDate).format('YYYY-MM-DD');
    }
    const timestamp = new Date().getTime(); // 时间戳,点查询的时候 不管条件有没有改变 都有触发查询
    e.timestamp = timestamp;
    this.commonArgs = e;

    let newactiveKey = '';
    if (this.state.securityType == '0') {
      // 债券
      newactiveKey = 'Bond';
    } else if (this.state.securityType == '2') {
      // 场外基金
      newactiveKey = 'OutsideFunds';
    } else if (this.state.securityType == '9') {
      // ETF
      newactiveKey = 'Etf';
    } else if (this.state.securityType == '7') {
      // 理财直融
      newactiveKey = 'DirectFinancing';
    } else if (this.state.securityType == '12') {
      // 非标
      newactiveKey = 'Nonstandard';
    } else if (this.state.securityType == '13' || this.state.securityType == '14') {
      // 交易所协议式回购
      newactiveKey = 'ExchangeNegotiatedRepo';
    } else if (this.state.securityType == '32' || this.state.securityType == '33') {
      // 买断式
      newactiveKey = 'InterbankBuyout';
    } else if (this.state.securityType == '8') {
      // 存款
      newactiveKey = 'DepositMoney';
    } else if (this.state.securityType == '5' || this.state.securityType == '6') {
      // 交易所回购
      newactiveKey = 'ExchangeRepo';
    } else if (this.state.securityType == '3' || this.state.securityType == '4') {
      // 银行间回购
      newactiveKey = 'InterbankRepo';
    } else if (this.state.securityType == '1') {
      // 股票
      newactiveKey = 'Stock';
      sessionStorage.setItem('Stock', this.state.HkStkType);
    } else if (this.state.securityType == '16' || this.state.securityType == '17') {
      // 债券借贷
      newactiveKey = 'BondLending';
    } else if (this.state.securityType == '20') {
      // 投资指令
      newactiveKey = 'Assets';
    } else if (this.state.securityType == '21') {
      // 委外投资
      newactiveKey = 'WeiWaiPost';
    } else if (this.state.securityType == '23' || this.state.securityType == '24') {
      // 股指期货
      newactiveKey = 'StockFuture';
    }

    if (newactiveKey != '') {
      let parentActiveKey = '';
      switch (newactiveKey) {
        case 'OutsideFunds':
          parentActiveKey = 'Etf';
          break;
        case 'ExchangeRepo':
          parentActiveKey = 'InterbankRepo';
          break;
        case 'ExchangeNegotiatedRepo':
          parentActiveKey = 'InterbankRepo';
          break;
        case 'Nonstandard':
          parentActiveKey = 'DirectFinancing';
          break;
        case 'InterbankBuyout':
          parentActiveKey = 'InterbankRepo';
          break;
        default:
          parentActiveKey = newactiveKey;
      }
      this.setState(
        {
          activeKey: parentActiveKey,
          childrenactiveKey: newactiveKey,
        },
        () => {
          this.setState({
            securityType: '',
          });

          this.getTableData();
        },
      );
    } else {
      this.getTableData();
    }
  };

  // 点击重置
  onClear = () => {
    this.commonArgs = {};
  };

  render() {
    const searchProps = {
      dataSource: [
        {
          dataIndex: ['startDate', 'endDate'],
          title: '日期区间',
          type: DATA_ENTRY.RANGEDATE,
          initialValue: [moment(), moment()],
          onRef: (ref) => {
            this.state.date = ref;
          },
        },
        {
          title: '组合',
          type: DATA_ENTRY.PRODUCTGROUPTREE,
          isMultiple: true,
          dataIndex: 'cpCode',
          tradeModel: ['BOOKKEEPING_MODE', 'COMMAND_MODE', 'VALUATION_BOOKKEEPING_MODEL'], // 不支持选估值解析模式的产品
          onRef: (ref) => {
            this.state.AdvancedSearchFormBeanRef = ref;
          },
        },
        {
          dataIndex: 'tradingCode',
          codeType: codeType.positioned,
          type: DATA_ENTRY.SECURITIESCODE,
          onChange: (e) => this.zqCodeChange(e),
          onRef: (ref) => (this.formGroupThis = ref),
        },
        {
          dataIndex: 'investmentType',
          title: '投资类型',
          type: DATA_ENTRY.SELECT,
          allowClear: true,
          dataSource: investmentTypeData,
        },
      ],
      onQuery: (e) => this.getSearchData(e),
      onClear: (e) => this.onClear(e),
    };

    return (
      <ContentPackage
        title='流水查询'
        contentHtml={
          <div className={style.bondDeviationDetail}>
            <Row>
              <AdvancedSearch {...searchProps} />
            </Row>

            <div style={{ marginTop: '10px' }} className={style.tabsOne}>
              <TabC
                tabSource={[
                  { title: '债券', key: 'Bond', content: <Bond args={this.state.bondArgs} /> },
                  {
                    title: '基金',
                    key: 'Etf',
                    content: (
                      <TabC
                        type='secondTab'
                        tabSource={[
                          { title: '场内（ETF）基金', key: 'Etf', content: <Etf args={this.state.etfArgs} /> },
                          { title: '场外基金', key: 'OutsideFunds', content: <OutsideFunds args={this.state.outsideFundsArgs} /> },
                        ]}
                        activeKey={this.state.childrenactiveKey}
                        onChange={this.childrentabOnclick}
                      />
                    ),
                  },
                  {
                    title: '回购',
                    key: 'InterbankRepo',
                    content: (
                      <TabC
                        type='secondTab'
                        tabSource={[
                          { title: '银行间质押式', key: 'InterbankRepo', content: <InterbankRepo args={this.state.interbankRepoArgs} /> },
                          { title: '交易所质押式', key: 'ExchangeRepo', content: <ExchangeRepo args={this.state.exchangeRepoArgs} /> },
                          { title: '交易所协议式', key: 'ExchangeNegotiatedRepo', content: <ExchangeNegotiatedRepo args={this.state.exchangeNegotiatedRepoArgs} /> },
                          { title: '银行间买断式', key: 'InterbankBuyout', content: <InterbankRepo args={this.state.interbankRepoArgs} InterbankBuyout={true} /> },
                        ]}
                        activeKey={this.state.childrenactiveKey}
                        onChange={this.childrentabOnclick}
                      />
                    ),
                  },
                  { title: '存款', key: 'DepositMoney', content: <DepositMoney args={this.state.depositMoneyArgs} /> },
                  { title: '股票', key: 'Stock', content: <Stock args={this.state.stockArgs} /> },
                  {
                    title: '非标',
                    key: 'DirectFinancing',
                    content: (
                      <TabC
                        type='secondTab'
                        tabSource={[
                          { title: '理财直融', key: 'DirectFinancing', content: <DirectFinancing args={this.state.directFinancingArgs} /> },
                          { title: '非理财直融', key: 'Nonstandard', content: <Nonstandard args={this.state.nonstandardArgs} /> },
                        ]}
                        activeKey={this.state.childrenactiveKey}
                        onChange={this.childrentabOnclick}
                      />
                    ),
                  },
                  { title: '资产管理计划', key: 'Assets', content: <Assets args={this.state.AssetsArgs} /> },
                  { title: '期货', key: 'StockFuture', content: <StockFuture args={this.state.stockFutureArgs} /> },
                ]}
                activeKey={this.state.activeKey}
                onChange={this.tabOnclick}
              />
            </div>
          </div>
        }
      />
    );
  }
}
